package com.jianyun.jyzs.model;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jianyun.jyzs.bean.LoginBean;
import com.jianyun.jyzs.bean.SignVersionBean;
import com.jianyun.jyzs.bean.UrlConfig;
import com.jianyun.jyzs.http.Api;
import com.jianyun.jyzs.http.CustomCallback;
import com.jianyun.jyzs.http.RetrofitHelper;
import com.jianyun.jyzs.model.imdoel.IJyLoginHelper;
import com.jianyun.jyzs.qrcode.qrcodemanager.QRCodeManager;
import com.jianyun.jyzs.utils.DeviceUtils;
import com.jianyun.jyzs.utils.Logger;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.NetUtil;
import com.jianyun.jyzs.utils.NetUtils;
import com.jianyun.jyzs.utils.SystemUtils;

import org.json.JSONException;
import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.jrmf360.rylib.wallet.JrmfWalletClient.getApplicationContext;

/**
 * Created by yangshijun on 2018/5/24.
 */

public class LoginModel implements IJyLoginHelper {

    private static LoginModel model;
    private Context context;

    private LoginModel() {
    }

    public static LoginModel getInstance() {
        if (null == model) {
            model = new LoginModel();
        }
        return model;
    }

    @Override
    public void getJyCenterUrl(final Context context, final String enterpriseCode, final OnGetJyUrlListener onJyLoginListener) {
        this.context = context;
        Api api = RetrofitHelper.builder().create(Api.class);
        api.getConfig("GetConfig", enterpriseCode, "jyzs", "Android", "1.0.2")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CustomCallback<UrlConfig>() {
                    @Override
                    protected void onResponse(UrlConfig response) {
                        if (response.isResult()) {
                            Log.i("test", "云中心：" + response.toString());
                            response.setEnterpriseCode(enterpriseCode);
                            initConfig();
                            //保存云中心URL
                            LoginCache.getInstance().setLoginCache(response);
                            onJyLoginListener.loginResult(true, response.toString());

                        } else {
                            onJyLoginListener.loginResult(false, response.getMessage());
                        }
                    }

                    @Override
                    protected void onException(String msg) {
                        onJyLoginListener.loginResult(false, msg);
                    }


                });
    }

    @Override
    public void startLogin(final String enterpriseCode, final String username, final String password, String appVersion, final OnLoginListener onLoginListener) {
        Api api = RetrofitHelper.builderErpHttp().create(Api.class);
        //Log.i("test","登录："+enterpriseCode+"\n"+username+"\n"+password+"\n"+phoneType+"\n"+osVersion);
        api.jyLogin("loginApp", enterpriseCode, username, password, "jyzs", "Android", appVersion)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CustomCallback<LoginBean>() {
                    @Override
                    protected void onResponse(LoginBean response) {
                        Log.i("test", "登录：" + response.toString());
                        if (response.isResult()) {
                            upPhoneInfo(enterpriseCode, response.getId());
                            //保存用户信息
                            LoginCache.getInstance().setUserInfo(username, password, response.getId());
                            //登录成功
                            onLoginListener.loginSuccess();
                            //获取签到版本
                            getSignVersion(enterpriseCode);
                            //上传设备ID以及userId


                        } else {
                            onLoginListener.loginException(response.getMessage());
                        }
                    }

                    @Override
                    protected void onException(String msg) {
                        onLoginListener.loginFailed();
                    }

                });
    }


    public void upPhoneInfo(String enterpriseCode, String userId) {
        //设备ID
        String androidID = DeviceUtils.getAndroidID(context);
        //厂商
        String deviceBrand = SystemUtils.getDeviceBrand();
        //型号
        String systemModel = SystemUtils.getSystemModel();
        //版本号
        String systemVersion = SystemUtils.getSystemVersion();
        //网络类型
        String networkType = NetUtils.getNetworkType(context);
        Api api = RetrofitHelper.builderErpHttp().create(Api.class);
        api.upPhoneInfo("EmployeeDeviceDG", enterpriseCode, androidID, deviceBrand, systemModel, "Android", systemVersion,
                "jyzs", userId, networkType , "jyzs", "Android", "1.0.2")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<Object>() {
                    @Override
                    public void onNext(Object o) {
                        try {
                            JSONObject jsonObject = new JSONObject(o.toString());
                            boolean result = jsonObject.getBoolean("result");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                });
    }


    /**
     * 上传RegistrationId
     */
    private void upRegistrationId(String userId) {
//        String rid = JPushInterface.getRegistrationID(getApplicationContext());
//        if (!rid.isEmpty()) {
//            Api api = RetrofitHelper.builderCeshiHttp().create(Api.class);
//            api.upRegId("SaveRegistration_id", userId, rid)
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribeOn(Schedulers.io())
//                    .subscribe(new Subscriber<Object>() {
//                        @Override
//                        public void onError(Throwable e) {
//                            e.printStackTrace();
//                        }
//
//                        @Override
//                        public void onCompleted() {
//
//                        }
//
//                        @Override
//                        public void onNext(Object o) {
//                            String s = new Gson().toJson(o);
//                            Log.i("test", "上传RegistrationId：" + s.toString());
//                        }
//                    });
//        }

    }

    /**
     * 获取考勤版本
     *
     * @param enterpriseCode
     */
    public void getSignVersion(final String enterpriseCode) {
        Api api = RetrofitHelper.builderNewSignHttp().create(Api.class);
        api.getSignViersion("GetKQGLVersion", enterpriseCode)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CustomCallback<SignVersionBean>() {
                    @Override
                    protected void onResponse(SignVersionBean response) {
                        Log.i("test", "企业号：" + enterpriseCode + "  获取版本：" + response.toString());
                        if (response.getResult()) {
                            LoginCache.getInstance().setSignVersion(response);
                        } else {
                            response.setVersion("0");
                            LoginCache.getInstance().setSignVersion(response);
                        }
                    }

                    @Override
                    protected void onException(String msg) {
                        SignVersionBean signVersionBean = new SignVersionBean();
                        signVersionBean.setVersion("0");
                        LoginCache.getInstance().setSignVersion(signVersionBean);
                    }
                });
    }

    private static void initConfig() {
/*
        EABConfig config = new EABConfig.Builder()
                .setAppServer(response.getRceServerURL())
                .setAppKey(response.getAPPKey())
//                配置小米 push
                .setMiPush("2882303761517578686", "5861757835686")
//                配置华为 push
                .enableHMS(true)
//                .setNaviServer("")
//                .setMediaServer("")
                .build();
        //rce lib 初始化
        TaskManager.init(context, config);
        ProviderConfig.init(context);*/
        new QRCodeManager.Config().setVibrateMode(false).setVoiceMode(false);
        //pin
        //PinAlbumBitmapCacheHelper.init(context);
    }
}
